/**
 * HSQLDBserver.java jCOLIBRI2 framework.
 *
 * @author Juan A. Recio-Garc�a. GAIA - Group for Artificial Intelligence
 * Applications http://gaia.fdi.ucm.es 04/07/2007
 */
package home.ex.todolist.server;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.HashMap;

import org.hsqldb.Server;

/**
 * Creates a data base server with the tables for the examples/tests using the
 * HSQLDB library.
 *
 * @author Juan A. Recio-Garcia
 * @version 1.0
 */
public class HSQLDBserver {

    static boolean initialized = false;
    private static Server server;

    /**
     * Initialize the server
     */
    public static void init() {
        if (HSQLDBserver.initialized) {
            return;
        }
        org.apache.commons.logging.LogFactory.getLog(HSQLDBserver.class).info("Creating data base ...");

        HSQLDBserver.server = new Server();
        HSQLDBserver.server.setDatabaseName(0, "todoDB");
        HSQLDBserver.server.setDatabasePath(0, "mem:todoDB;sql.enforce_strict_size=true");

        HSQLDBserver.server.setLogWriter(null);
        HSQLDBserver.server.setErrWriter(null);
        HSQLDBserver.server.setSilent(true);
        HSQLDBserver.server.start();

        HSQLDBserver.initialized = true;
        try {
            Class.forName("org.hsqldb.jdbcDriver");

            final PrintStream out = new PrintStream(new ByteArrayOutputStream());
            final Connection conn = DriverManager.getConnection("jdbc:hsqldb:hsql://localhost/todoDB", "sa", "");
            final SqlFile file = new SqlFile(new File(FileIO.findFile("src/main/resources/TodoListApp.sql").getFile()),
                    false, new HashMap());
            file.execute(conn, out, out, true);

            org.apache.commons.logging.LogFactory.getLog(HSQLDBserver.class).info("Data base generation finished");

        } catch (final Exception e) {
            org.apache.commons.logging.LogFactory.getLog(HSQLDBserver.class).error(e);
        }

    }

    /**
     * Shutdown the server
     */
    public static void shutDown() {

        if (HSQLDBserver.initialized) {
            HSQLDBserver.server.stop();
            HSQLDBserver.initialized = false;
        }
    }

    /**
     * Testing method
     */
    public static void main(final String[] args) {
        HSQLDBserver.init();
        HSQLDBserver.shutDown();
        System.exit(0);
    }
}
